#!/usr/bin/env python
# -*- conding: utf-8 -*-

"""
@Time     : 2024/8/12 22:20
@Author   : liujingmao
@File     : gaode_weather_tool.py
"""

import json
import os
from typing import Any, Type

import dotenv
import requests
# 使用langchain_core==0.2.38这个版本
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import BaseTool

dotenv.load_dotenv()


class GaodeWeatherArgsSchema(BaseModel):
    city: str = Field(description="请输入需要查询天气预报的目标城市，例如：广州")


class GaodeWeatherTool(BaseTool):
    """根据输入的城市名查询天气"""
    name = "gaode_weather_tool"
    description = "当你想查询天气或者与天气相关的问题时可以使用的工具"
    args_schema: Type[BaseModel] = GaodeWeatherArgsSchema

    def _run(self, *args: Any, **kwargs: Any) -> str:
        """根据输入的城市名查询天气信息"""
        try:
            # 1. 获取高德API的key
            gaode_api_key = os.getenv("GAODE_API_KEY")
            if not gaode_api_key:
                return f"没有配置相关的高德API_KEY"

            # 2. 从传递的kwargs获取city
            city = kwargs.get("city", "")

            api_domain = "https://restapi.amap.com/v3"
            session = requests.session()
            # 3. 根据城市获取城市的行政编码
            city_response = session.request(
                method="GET",
                url=f"{api_domain}/config/district?keywords={city}&subdistrict=0&key={gaode_api_key}",
                headers={"Content-Type": "application/json;charset=UTF-8"},
            )
            city_response.raise_for_status()
            city_data = city_response.json()
            if city_data.get("info") == "OK":
                ad_code = city_data["districts"][0]["adcode"]
                # 4. 根据行政编码调用天气api
                weather_response = session.request(
                    method="GET",
                    url=f"{api_domain}/weather/weatherInfo?key={gaode_api_key}&city={ad_code}&extensions=all&output=json",
                    headers={"Content-Type": "application/json;charset=UTF-8"},
                )
                weather_response.raise_for_status()
                weather_data = weather_response.json()
                if weather_data.get("info") == "OK":
                    # 5. 返回结果
                    return json.dumps(weather_data)
            # 6. 关闭会话
            session.close()
            return f"get{city}天气信息失败v1"
        except Exception as e:
            return f"get{kwargs.get('city', '')}天气信息失败v2"


gaode_weather_tool = GaodeWeatherTool()
print(gaode_weather_tool.invoke({"city": "深圳"}))

"""
{"status": "1", "count": "1", "info": "OK", "infocode": "10000", "forecasts": [{"city": "\u6df1\u5733\u5e02", "adcode": "440300", "province": "\u5e7f\u4e1c", "reporttime": "2025-01-07 23:00:15", "casts": [{"date": "2025-01-07", "week": "2", "dayweather": "\u6674", "nightweather": "\u591a\u4e91", "daytemp": "22", "nighttemp": "14", "daywind": "\u5317", "nightwind": "\u5317", "daypower": "1-3", "nightpower": "1-3", "daytemp_float": "22.0", "nighttemp_float": "14.0"}, {"date": "2025-01-08", "week": "3", "dayweather": "\u591a\u4e91", "nightweather": "\u9634", "daytemp": "21", "nighttemp": "14", "daywind": "\u5317", "nightwind": "\u5317", "daypower": "1-3", "nightpower": "1-3", "daytemp_float": "21.0", "nighttemp_float": "14.0"}, {"date": "2025-01-09", "week": "4", "dayweather": "\u9634", "nightweather": "\u6674", "daytemp": "19", "nighttemp": "10", "daywind": "\u5317", "nightwind": "\u5317", "daypower": "1-3", "nightpower": "1-3", "daytemp_float": "19.0", "nighttemp_float": "10.0"}, {"date": "2025-01-10", "week": "5", "dayweather": "\u6674", "nightweather": "\u6674", "daytemp": "17", "nighttemp": "9", "daywind": "\u5317", "nightwind": "\u5317", "daypower": "1-3", "nightpower": "1-3", "daytemp_float": "17.0", "nighttemp_float": "9.0"}]}]}

"""
